package mvc.exporter.impl;

import java.awt.Image;
import java.awt.image.RenderedImage;
import java.io.File;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

import javax.imageio.ImageIO;

import mvc.exporter.IExporter;
import mvc.gui.IFileChooser;
import mvc.gui.impl.LocalFileChooser;
import mvc.gui.impl.LocalFileChooser.DialogType;

public class LocalFileExporter implements IExporter {
	private IFileChooser fileChooser;
	private String filePath;
	private String fileExt;

	public LocalFileExporter() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public boolean prepareSave() {
		List<String> afe = new LinkedList<String>();
		for (String s : javax.imageio.ImageIO.getReaderFileSuffixes()) {
			afe.add(s);
		}
		fileChooser = new LocalFileChooser(DialogType.SAVE_DIALOG, afe);
		if (fileChooser.showFileChooser()) {
			filePath = fileChooser.getFile().getAbsolutePath();
			fileExt = fileChooser.getFileExtension();
			System.out.println("User choosed: " + filePath + " and " + fileExt);
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void saveImage(Image image, String filename) throws IOException {
		try {
			ImageIO.write((RenderedImage) image, fileExt, new File(filePath + File.separator 
					+ filename.substring(0, filename.lastIndexOf(".")) + "." + fileExt));
			System.out.println("  saved as	" + filePath + File.separator +
					 filename.substring(0, filename.lastIndexOf(".")) + "." + fileExt);
		} catch (ClassCastException e) {
			System.out
					.println("Can not write file since the Object representing "
							+ filename + " is not a RenderedImage");
			e.printStackTrace();
		}
	}

}
